import 'dart:developer';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/utils/toast_utils.dart';
import 'package:sports_new/utils/widget_utils.dart';
import 'package:sports_new/widgets/select_bottomsheet.dart';

import 'base/qkd_text.dart';

class PicturePreview extends StatefulWidget {
  const PicturePreview({
    super.key,
    this.imageUrl,
    this.imageUrlArray,
    this.initialIndex,
    this.path, this.needSave = false,
  });
  final List<String>? imageUrlArray;
  final int? initialIndex;
  final String? imageUrl;
  final String? path;
  final bool needSave;

  @override
  State<PicturePreview> createState() => _PicturePreviewState();
}

class _PicturePreviewState extends State<PicturePreview> {
  final PhotoViewControllerBase _photoViewController = PhotoViewController();
  late PageController pageC;
  int currentIndex = 0;

  @override
  void initState() {
    super.initState();
    if (widget.imageUrlArray != null) {
      currentIndex = widget.initialIndex ?? 0;
      pageC = PageController(initialPage: currentIndex);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: GestureDetector(
        onTap: () => Get.back(),
        onLongPress: () async {
          // final a = await Permission.photos.request();
          // log('$a');
          if(!widget.needSave) return;
          final result = await Get.bottomSheet(SelectBottomSheet(['保存到相册']));
          if (result == 0) {
            EasyLoading.show();
            try {
              final response = await Dio().get(
                  widget.imageUrlArray![currentIndex],
                  options: Options(responseType: ResponseType.bytes));
              final result = await ImageGallerySaver.saveImage(
                  Uint8List.fromList(response.data),
                  quality: 80);
              if (result['isSuccess'] == true) {
                ToastUtils.show('保存成功');
              } else {
                EasyLoading.dismiss();
              }
            } catch (e) {
              log('save image error');
              EasyLoading.dismiss();
            }
          }
        },
        child: widget.imageUrlArray != null
            ? Stack(
                alignment: Alignment.bottomCenter,
                children: [
                  PhotoViewGallery.builder(
                    scrollPhysics: const BouncingScrollPhysics(),
                    // backgroundDecoration:
                    //     const BoxDecoration(color: Colors.black45),
                    builder: (BuildContext context, int index) {
                      return PhotoViewGalleryPageOptions(
                        minScale: PhotoViewComputedScale.contained * 0.5,
                        onTapUp: (context, details, controllerValue) {
                          log('onTapUp');
                          Get.back();
                        },
                        imageProvider: CachedNetworkImageProvider(
                            widget.imageUrlArray![index]),
                        // initialScale: PhotoViewComputedScale.contained * 0.8,
                        // heroAttributes:
                        //     PhotoViewHeroAttributes(tag: widget.imageUrlArray![index].id),
                      );
                    },
                    itemCount: widget.imageUrlArray!.length,
                    loadingBuilder: (context, event) => Center(
                      child: Container(
                          width: 40,
                          height: 40,
                          child: CircularProgressIndicator(
                              value: event?.cumulativeBytesLoaded.toDouble())),
                    ),

                    // backgroundDecoration: widget.backgroundDecoration,
                    pageController: pageC,
                    onPageChanged: (index) {
                      currentIndex = index;
                      update();
                    },
                  ),
                  Positioned(
                      child: SafeArea(
                    child: QkdText(
                      '${currentIndex + 1}/${widget.imageUrlArray!.length}',
                      color: Colours.white,
                      fontWeight: FontWeight.w500,
                      fontSize: 16,
                    ),
                  ))
                ],
              )
            : PhotoView(
                loadingBuilder: (context, event) => Center(
                    child: Container(
                        width: 40,
                        height: 40,
                        child: CircularProgressIndicator(
                            value: event?.cumulativeBytesLoaded.toDouble()))),
                backgroundDecoration:
                    const BoxDecoration(color: Colors.black45),
                controller: _photoViewController,
                minScale: PhotoViewComputedScale.contained * 0.5,
                maxScale: PhotoViewComputedScale.covered * 3.0,
                imageProvider: widget.imageUrl == null
                    ? Image.asset(widget.path!).image
                    : NetworkImage(widget.imageUrl!),
              ),
      ),
    );
  }
}
